package com.nidu.demo.common.validation;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.PhoneUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class MobileValidator implements ConstraintValidator<Mobile, String> {

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // 如果手机号为空，默认不校验，即校验通过
        if (CharSequenceUtil.isEmpty(value)) {
            return true;
        }
        // 校验手机
        if(PhoneUtil.isMobile(value)){
            return true;
        } else {
            // 自定义错误信息
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("手机号格式不正确").addConstraintViolation();
            return false;
        }
    }
}
